package threading;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-07-05
 * Time: 21:17
 */
public class ThreadDemo27 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {//泛型写什么，call就返回什么
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 0; i <= 1000; i++) {
                    sum += i;
                }
                return sum;
            }
        };

        //还需要个线程，来执行这个任务
        //Thread不能直接传入callable，需要包装一层
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);

        t.start();

        System.out.println(futureTask.get());//get()方法用来获取任务的返回值，和join()类似，如果t线程未算出结果，就阻塞等待
    }
}
